
//
//  HomeViewController.m  
//  DoctorFAQs
//
//  Created by zjq on 17/2/9.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeHeaderView.h"
#import "HomeCollectionView.h"
#import "CollectionViewCell.h"
#import "ZLookSearchView.h"
#import "SearchViewController.h"
#import "ConsultingDoctorViewController.h"
#import "ZDoctorReplyViewController.h"
#import "ZLookFriendViewController.h"
#import "ZTacticsViewController.h"
#import "ZPlayVideoViewController.h"
#import "LZLoginViewController.h"
#import "ZHomeAdvertViewController.h"
#import "JNavigationController.h"
#import "ZUnpaidView.h"

#import "JTAlertView.h"
#import "ZHomeMidCell.h"
#import "ZAgainPostView.h"
#import "ZSuccessfulAgainView.h"
#import "ZPayViewController.h"
#import "LZUserInfo.h"

#import "ZHomeHeaderMoedel.h"
#import "ZFMDBTool.h"// 数据库
//#import "ZAppraiseViewController.h"
static NSString * const kJHCollectionViewIdentifier = @"JHCollectionViewIdentifier"; /**< Home界面集合视图重用标志 */
static NSString * const kJHomeTabViewIdentifier = @"JHTableViewIdentifier";

@interface HomeViewController ()<homeHeaderViewDelegate,UITableViewDelegate,UITableViewDataSource> {
    NSArray * _imageName;
}
//@property (nonatomic,strong) UIScrollView * rootScrollView;
@property (nonatomic,strong) UITableView * mainTableView;
@property (nonatomic,strong) HomeHeaderView * homeHeaderView;
@property (nonatomic,strong) UICollectionView * homeCollectionView;
@property (nonatomic,strong) ZLookSearchView * searchView;
@property (nonatomic,strong) ZAgainPostView * againPostView;
@property (nonatomic,strong) ZSuccessfulAgainView * successAgainView;
@property (nonatomic,strong) ZUnpaidView * unpaidView;
@property (nonatomic,strong) LZUserInfo * userInfo;
@property (nonatomic,strong) NSString * pay; // 是否支付
@property (nonatomic,strong) NSString * is_read;// 是否已读
@property (nonatomic,strong) NSString * pid;// 未支付的订单号
@property (nonatomic,strong) UIImageView * testImage;


@property (nonatomic,strong) NSMutableArray <ZHomeHeaderMoedel *>* headerModel;
@property (nonatomic,strong) NSMutableArray * imageURLArray;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"issueExampleNotification"];
    [[NSNotificationCenter defaultCenter] removeObserver:@"againLogin"];
    [[NSNotificationCenter defaultCenter] removeObserver:@"LogOut"];
    [[NSNotificationCenter defaultCenter] removeObserver:@"paySuess"];
    [[NSNotificationCenter defaultCenter] removeObserver:@"LogSuess"];
    
}
- (void)setPay:(NSString *)pay {
    _pay = pay;
    if ([_pay isEqualToString:@"1"]) {
        [self.view addSubview:self.unpaidView];
        ESWeak(self, pWeakSelf);
        self.unpaidView.GoPayBtnBolck = ^() {
            //        NSLog(@"我再跳转");
            [pWeakSelf.unpaidView removeFromSuperview];
            ZPayViewController * vc = [[ZPayViewController alloc]init];
            vc.pid = pWeakSelf.pid;
            vc.isHome = YES;
            [pWeakSelf.navigationController pushViewController:vc animated:YES];
        };

    }else {
        
    }
}
- (void)initialzeDatas {
    _imageName = @[@"consult_doc",@"doc_answer",@"Patients",@"strategy"];
    _is_read = @"0";
    _headerModel = [@[] mutableCopy];
    _imageURLArray = [@[] mutableCopy];
    _userInfo = [LZUserInfo getUserInfo];

}
// 界面初始化
- (void)initlizeInterface {
//    self.view.backgroundColor = MYGRAYCOLOR;
    //分享按钮
    UIButton * rightBtn = [[UIButton alloc] init];
    rightBtn.frame = CGRectMake(0, 0, 16, 13);
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"btn_share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBitem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    self.navigationItem.rightBarButtonItem = rightBitem;
    self.navigationItem.titleView = self.searchView;
    self.view .backgroundColor = KHColorFromRGB(0xffffff);
    [self.view addSubview:self.mainTableView];
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.top.equalTo(self.view);
        make.height.equalTo(self.view);
    }];
    self.mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    
        [self homeNetWroking];
        [self.mainTableView.mj_header  endRefreshing];
    }];
    if([[NSUserDefaults standardUserDefaults] dataForKey:@"homeData"]){
        NSData * data = [[NSUserDefaults standardUserDefaults] dataForKey:@"homeData"];
        NSDictionary * dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];\
        [self handleDataWithDict:dic];
    }else {
        [self.mainTableView.mj_header beginRefreshing];
    }

    
    //注册发布 再次发布的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(issueExample:) name:@"issueExampleNotification" object:nil];
    // 修改密码成功后，再次登录通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(againLoginNotification:) name:@"againLogin" object:nil];
    // 退出登录的 通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Homerefresh) name:@"LogOut" object:nil];
    // 登录成功的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Homerefresh) name:@"LogSuess" object:nil];
    // 支付完成后的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PayRefresh) name:@"paySuess" object:nil];

}

// 修改密码成功后，再次登录通知
- (void)againLoginNotification:(NSNotification *)notification {
    [YJProgressHUD showMessage:@"密码修改成功，重新登录" inView:self.view];
//    [self.mainTableView.mj_header beginRefreshing];
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        LZLoginViewController *loginVC = [[LZLoginViewController alloc] init];
        JNavigationController *tempNav = [[JNavigationController alloc] initWithRootViewController:loginVC];
        [weakSelf presentViewController:tempNav animated:YES completion:nil];
    });
    
}
// 退出登录后的刷新
- (void)Homerefresh {
    [self.mainTableView.mj_header beginRefreshing];
}
// 支付完成的刷新
- (void)PayRefresh {
//    self.pay = @"0";
//    [self.unpaidView removeFromSuperview];
    [self.mainTableView.mj_header beginRefreshing];
}
// 发布病情案例的通知方法
- (void)issueExample:(NSNotification *)notification {
    NSString * qid = notification.userInfo[@"pid"];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.againPostView.pid = qid;
        [window addSubview:self.againPostView];
}
// 再次发布的block方法
- (void)againPostTheExample {
    NSLog(@"再次发布");
    [self.againPostView removeFromSuperview];
    [self sendAgainQuestion];

}

- (void)sendAgainQuestion {
    NSDictionary * dict = @{@"pid":self.againPostView.pid};
    [YJProgressHUD showProgress:@"再次发布中" inView:self.view];
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:dict paramarsSite:@"Index/againProblem" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"再次发布成功" inView:self.view];
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            [window addSubview:self.successAgainView];
        }else {
            [YJProgressHUD showMessage:@"发布失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"网络请求失败" inView:self.view];
    }];
}

// 分享按钮的方法
- (void)shareAction {
    if (_userInfo.uid && ![_userInfo.uid isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"假装在分享" inView:self.view];
    }else {
        [self pointOutLogin];
    }

    
}

// 搜索按钮
-(void)jumpSearchAction {
    SearchViewController * searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

// 表格视图协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView  {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ESWeak(self, hWeakSelf);
    ZHomeMidCell * cell = [tableView dequeueReusableCellWithIdentifier:kJHomeTabViewIdentifier forIndexPath:indexPath];
    if (_imageURLArray&&_imageURLArray.count!= 0) {
        cell.imageurlArray = _imageURLArray;
    }
    cell.read = _is_read;
    cell.bolck = ^(NSInteger index) {
        [hWeakSelf jumpOtherVCWith:index];
    };
    return cell;
}
// 跳转咨询医生等4个界面
- (void)jumpOtherVCWith:(NSInteger)idx {
    if (idx == 0) {
        if (!_pay || [_pay isEqualToString:@"1"]) {
            [YJProgressHUD showMessage:@"有未支付订单" inView:self.view];
            [self.view addSubview:self.unpaidView];
            return;
        }
        ConsultingDoctorViewController * CDVC = [[ConsultingDoctorViewController alloc] init];
        [self.navigationController pushViewController:CDVC animated:YES];
    }else if (idx == 1) {
        if (_userInfo.uid && ![_userInfo.uid isEqualToString:@""]) {
            ZDoctorReplyViewController * ZDRVC = [[ZDoctorReplyViewController alloc] init];
            [self.navigationController pushViewController:ZDRVC animated:YES];
        }else {
            [self pointOutLogin];
        }
        
    }else if (idx == 2) {
        ZLookFriendViewController * ZLZVC = [[ZLookFriendViewController alloc] init];
        [self.navigationController pushViewController:ZLZVC animated:YES];
    }else if (idx == 3) {
        ZTacticsViewController * ZTVC = [[ZTacticsViewController alloc] init];
        [self.navigationController pushViewController:ZTVC animated:YES];
    }else {
        
    }
}
//未登录的弹窗提示
- (void)pointOutLogin {
    JTAlertView * alert = [[JTAlertView alloc] init];
    [alert showPleaseLoginFromviewController:self loginHandel:^{
        LZLoginViewController * logVC = [[LZLoginViewController alloc] init];
        JNavigationController * navVc = [[JNavigationController alloc] initWithRootViewController:logVC];
        [self presentViewController:navVc animated:YES completion:nil];
    }];
}



//点击滚动视图
- (void)intoAVControllerWithIndex:(NSInteger)imageIndex {
    NSLog(@"%ldhomeindex",(long)imageIndex);
    if (_headerModel) {
        ZHomeHeaderMoedel * model = _headerModel[imageIndex];
        if ([model.type intValue]== 2) {
            ZPlayVideoViewController * zPlayVC = [[ZPlayVideoViewController alloc] init];
            zPlayVC.vid = model.adID;
            [self .navigationController pushViewController:zPlayVC animated:YES];
            
        }else if ([model.type intValue] == 1) {
            ZHomeAdvertViewController * zHomeVC = [ZHomeAdvertViewController alloc];
            zHomeVC.URLString = [NSString stringWithFormat:@"%@%@",TestURL,model.url];
            
            [self.navigationController pushViewController:zHomeVC animated:YES];
            return;
        }
    }
    
}

// 首页网络请求
- (void)homeNetWroking {
    ESWeak(self, HWeakSelf);
    
    [YJProgressHUD showProgress:@"正在刷新" inView:self.view];
    NSString * hUid = _userInfo.uid ? _userInfo.uid : @""; // 对nil id的处理
    NSDictionary * dict = @{@"uid":hUid};
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:dict paramarsSite:@"Index/index" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"加载成功" inView:HWeakSelf.view];
            [HWeakSelf handleDataWithDict:dict];
//            [self testDIct:dict];
        }else {
            [YJProgressHUD showMessage:@"请求错误" inView:HWeakSelf.view];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"网络请求错误" inView:self.view];

    }];
}

- (void)testDIct:(NSDictionary *)dict {
    [_testImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IconURL,@"/Uploads/2017-03-13/jycl.png"]]];
}
// 根据返回的字典处理数据
- (void)handleDataWithDict:(NSDictionary *)dict {
    NSLog(@"%@",dict);
    //处理滚动
    NSArray * adArray = dict[@"list"][@"ad"];
    [_headerModel removeAllObjects];
    for (NSDictionary * dict in adArray) {
        ZHomeHeaderMoedel * model = [[ZHomeHeaderMoedel alloc] initWithDict:dict];
        [_headerModel addObject:model];
    }
    self.homeHeaderView.modelArray = _headerModel;
    // 处理4张图
    NSMutableDictionary * imageDict = dict[@"list"][@"img"];
    [_imageURLArray removeAllObjects];
    [imageDict removeObjectForKey:@"id"];
    for (NSString * key in imageDict.allKeys) {
        NSString * url = [NSString stringWithFormat:@"%@%@",IconURL,imageDict[key]];
        [_imageURLArray addObject:url];
    }
    _is_read = dict[@"list"][@"is_read"];
    self.pay = dict[@"list"][@"is_pay"];
    self.pid = dict[@"list"][@"pid"];
    [_mainTableView reloadData];
//    [self findDictBankWithDict:dict]; //将字典存入数据库
     NSData * data = [NSKeyedArchiver archivedDataWithRootObject:dict];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"homeData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
//    NSData * Newdata = [[NSUserDefaults standardUserDefaults] dataForKey:@"homeData"];
//    NSDictionary * asdasd = [NSKeyedUnarchiver unarchiveObjectWithData:Newdata];
//    NSLog(@"23123");

    
}
// 建立首页表 - 4张图的表
//-(void)foundDataBank; {
//    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"Home.sqlite" dbHandler:^(FMDatabase *Z_db) {
//        NSString *cSql = @"CREATE TABLE IF NOT EXISTS Home (id INTEGER PRIMARY KEY, imageName TEXT NOT NULL,image blob)";
//        BOOL res = [Z_db executeUpdate:cSql];
//        if (!res) {
//            NSLog(@"error when creating db table");
//        } else {
//            NSLog(@"succ to creating db table");
//        }
//    }];
//}
// 创建首页整个字典的 表
-(void)foundHeadDataBank {
    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"HomeHead.sqlite" dbHandler:^(FMDatabase *Z_db) {
        NSString *cSql = @"CREATE TABLE IF NOT EXISTS HomeHead (id INTEGER PRIMARY KEY,dictName TEXT NOT NULL,dict blob)";
        BOOL res = [Z_db executeUpdate:cSql];
        if (!res) {
            NSLog(@"error when creating db table");
        } else {
            NSLog(@"succ to creating db table");
        }
    }];
}
- (void)findDataBank {
    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"HomeHead.sqlite" dbHandler:^(FMDatabase *Z_db) {
        NSString *qSql = [NSString stringWithFormat:@"SELECT * FROM HomeHead where dictName like '%@'",@"dictName"];
        FMResultSet *set = [Z_db executeQuery:qSql];
        //如果找不到就刷新
        // 如果有首页的数据
        if([set next]) {
            NSData * data = [set dataForColumn:@"dict"];
            if (data) {
                NSDictionary *status = [NSKeyedUnarchiver unarchiveObjectWithData:data];
//                [self handleDataWithDict:status];
//                [self chulibendiShuJu:status];
                
            }

        }else {
            // 没有则去进行首页的刷新
            [self.mainTableView.mj_header beginRefreshing];
        }
        
    }];
    
}

- (void)findDictBankWithDict:(NSDictionary *)dcit {
    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"HomeHead.sqlite" dbHandler:^(FMDatabase *Z_db) {
        NSString *qSql = [NSString stringWithFormat:@"SELECT * FROM HomeHead where dictName like '%@'",@"HdictName"];
        FMResultSet *set = [Z_db executeQuery:qSql];

        if([set next]) {
            NSData * data = [set dataForColumn:@"dict"];
//            NSDictionary *status = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            if (data) {
                [self upDataWithDict:dcit];
            }else {
                [self insetDataWithDict:dcit];
            }
            
        }else {
            // 没有则去进行插入  有则update
            [self insetDataWithDict:dcit];
        }
    }];

}
- (void)insetDataWithDict:(NSDictionary *)dict {
    
        
        [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"HomeHead.sqlite" dbHandler:^(FMDatabase *Z_db) {
            NSString * sql = @"insert into HomeHead (dictName,dict) values(?,?)";
            NSData * data = [NSKeyedArchiver archivedDataWithRootObject:dict];
            BOOL res = [Z_db executeUpdate:sql,@"HdictName",data];
            if (!res) {
                NSLog(@"error to insert data");
            } else {
                NSLog(@"succ to insert data");
            }
        }];
    
    
    
}
- (void)upDataWithDict:(NSDictionary *)dict {
    
        [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"HomeHead.sqlite" dbHandler:^(FMDatabase *Z_db) {
            
            NSString *uSql = @"UPDATE HomeHead SET dict = ? WHERE  dictName = ?";
            NSData * data = [NSKeyedArchiver archivedDataWithRootObject:dict];
            BOOL res = [Z_db executeUpdate:uSql,data,@"HdictName"];
            if (!res) {
                NSLog(@"error to UPDATE data");
            } else {
                NSLog(@"succ to UPDATE data");
                
            }
        }];
    
    
//}

//    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"HomeHead.sqlite" dbHandler:^(FMDatabase *Z_db) {
//        NSString * sql = @"UPDATE HomeHead SET dict = ? WHERE  dictName = 'HdictName' ";
//        NSData * data = [NSKeyedArchiver archivedDataWithRootObject:dict];
//        BOOL res = [Z_db executeUpdate:sql,data];
//        if (!res) {
//            NSLog(@"error to UPDATE data");
//        } else {
//            NSLog(@"succ to UPDATE data");
//        }
//    }];
//    [[ZFMDBTool sharedInstance] execSqlInFmdb:@"DoctorFAQs" dbFileName:@"HomeHead.sqlite" dbHandler:^(FMDatabase *Z_db) {
//        NSString * dsql = @"DELETE FROM HomeHead WHERE dictName = dictName";
//        BOOL res = [Z_db executeUpdate:dsql];
//        if (res) {
//            
//            NSString * sql = @"insert into HomeHead (dictName,dict) values(?,?)";
//            NSData * data = [NSKeyedArchiver archivedDataWithRootObject:dict];
//            BOOL res = [Z_db executeUpdate:sql,@"dictName",data];
//            if (!res) {
//                NSLog(@"error to insert data");
//            } else {
//                NSLog(@"succ to insert data");
//            }
//
//        }
//    }];
    
}



//lazy
-(HomeHeaderView *)homeHeaderView {
    if (_homeHeaderView) {
        return _homeHeaderView;
    }
    _homeHeaderView = [[HomeHeaderView alloc] init];
    _homeHeaderView.frame = CGRectMake(0, 0, SCREEN_Width, 160 *ysIZE);
    _homeHeaderView.homeHeaderDelagate = self;
    [_homeHeaderView.searchBtn addTarget:self action:@selector(jumpSearchAction) forControlEvents:UIControlEventTouchUpInside];
    return _homeHeaderView;
}

- (UITableView *)mainTableView {
    if (_mainTableView) {
        return _mainTableView;
    }
    _mainTableView  = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _mainTableView.showsVerticalScrollIndicator = NO;
    _mainTableView.tableHeaderView = self.homeHeaderView;
    _mainTableView.tableFooterView = [UIView new];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    _mainTableView.rowHeight = 315*ysIZE;
    _mainTableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [_mainTableView registerClass:[ZHomeMidCell class] forCellReuseIdentifier:kJHomeTabViewIdentifier];
    return _mainTableView;
}

- (ZLookSearchView *)searchView {
    if (_searchView) {
        return _searchView;
    }
    _searchView = [[ZLookSearchView alloc] init];
    _searchView.frame = CGRectMake(0, 0, 250*xsIZE, 60*ysIZE);
    _searchView.searchImageView.hidden = YES;
    _searchView.backgroundView.backgroundColor = MYGRAYCOLOR;
    [_searchView.searchBtn addTarget:self action:@selector(jumpSearchAction) forControlEvents:UIControlEventTouchUpInside];
    return _searchView;
}

- (ZAgainPostView *)againPostView {
    __weak typeof(self) weakSelf = self;
    if (_againPostView) {
        return _againPostView;
    }
    _againPostView = [[ZAgainPostView alloc] init];
    _againPostView.frame = CGRectMake(0, 0, SCREEN_Width, SCREEN_Height);
    _againPostView.AgainPostBlock = ^() {
        [weakSelf againPostTheExample];
    };
    return _againPostView;
}

- (ZSuccessfulAgainView *)successAgainView {
    if (_successAgainView) {
        return _successAgainView;
    }
    _successAgainView = [[ZSuccessfulAgainView alloc] init];
    _successAgainView.frame = CGRectMake(0, 0, SCREEN_Width, SCREEN_Height);
    return _successAgainView;
}
-(ZUnpaidView *)unpaidView {
    if (_unpaidView) {
        return _unpaidView;
    }
    ESWeak(self, hWeakSelf);
    _unpaidView = [[ZUnpaidView alloc] init];
    _unpaidView.frame = CGRectMake(0, 0, SCREEN_Width, SCREEN_Height);
    return _unpaidView;
}
@end
